package com.amkai.mobile.utils.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class MobileDb {

	private SQLiteDatabase db;
	private final Context context;
	private final MobileDBhelper dbhelper;

	public MobileDb(Context c) {
		context = c;
		dbhelper = new MobileDBhelper(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
	}

	public void close() {
		db.close();
	}

	public void open() throws SQLiteException {
		try {
			db = dbhelper.getWritableDatabase();
		} catch (SQLiteException ex) {
			Log.v("open exception caught", ex.getMessage());
			db = dbhelper.getReadableDatabase();
		}
	}

	public static String getLoginParameter(Context cont, String columnName) {
		String result = null;
		Cursor c = null;
		MobileDb mdb = new MobileDb(cont);
		mdb.open();
		try {
			c = mdb.getConnection(Constants.CONNECTION_TABLE_NAME);

			if (c.moveToFirst()) {
				do {
					result = c.getString(c.getColumnIndex(columnName));
				} while (c.moveToNext());
			}
		} finally {
			c.deactivate();
			mdb.close();
		}
		return result;
	}

	
	
	public static long insertConnection(Context cont, String username, String password, String server) {
		Long result;

		MobileDb mdb = new MobileDb(cont);
		mdb.open();

		try {

			ContentValues newTaskValue = new ContentValues();
			newTaskValue.put(Constants.USERNAME, username);
			newTaskValue.put(Constants.PASSWORD, password);
			newTaskValue.put(Constants.SERVER, server);
			newTaskValue.put(Constants.LICENSE, "TRUE");
			result = mdb.db.insert(Constants.CONNECTION_TABLE_NAME, null, newTaskValue);

		} catch (SQLiteException ex) {
			Log.v("open exception caught", ex.getMessage());
			result = -1L;
		} finally {
			mdb.close();
		}

		return result;
	}

	public Cursor getConnection(String tableName) {
		Cursor c = db.query(tableName, null, null, null, null, null, null);
		// c.deactivate();
		return c;
	}

	public void deleteConnection() {
		db.delete(Constants.CONNECTION_TABLE_NAME, null, null);
	}

}
